<?php

namespace app\common\model\banxi\course;

use app\common\enums\CourseStatusEnum;
use app\common\model\banxi\student\StudentCourse;
use app\common\model\common\BaseModel;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 课程字典
 */
class Course extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_course';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'statusCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'courseType' => 'string',
        'courseLevel' => 'string',
        'courseDifficult' => 'string',
        'courseBook' => 'string',
        'courseExperience' => 'boolean',
        'vocabularyRandom' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];
    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                         ｜
    //-----------------------------------------------------------------------------------

    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new CourseStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->with(['bookInfo', 'difficultInfo', 'levelInfo', 'typeInfo'])
            ->order('id', 'desc')
            ->where($where)->paginate(['page' => $page, 'list_rows' => $limit]);
    }

    public function getListStudentPage(string $studentId, array $where, string $page = "1", int $limit = 10)
    {
        $studentCourse = new StudentCourse();
        $courseIds = $studentCourse->listByStudentId($studentId);
        $where[] = ['id', 'not in', $courseIds];
        return $this->listEntityPage($where, $page, $limit);
    }

    public function getListStudentOpenPage(bool $isPractice, string $studentId, array $where, string $page = "1", int $limit = 10)
    {
        if ($isPractice) {
            $where[] = ['courseExperience', '=', 1];
        } else {
            $studentCourse = new StudentCourse();
            $courseIds = $studentCourse->listByStudentId($studentId);
            if (empty($courseIds)) {
                $where[] = ['id', '=', 0];
            } else {
                $where[] = ['id', 'in', $courseIds];
            }
        }
        return $this->listEntityPage($where, $page, $limit);
    }

    public function listEntityPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->with(['bookInfo', 'difficultInfo', 'levelInfo', 'typeInfo'])->where($where)->paginate(['page' => $page, 'list_rows' => $limit]);
    }

    public function getInfo(array $where)
    {
        return $this->with(['bookInfo', 'difficultInfo', 'levelInfo', 'typeInfo'])
            ->order('id', 'desc')
            ->where($where)->find();
    }

    public function saveOrUpdate(array $param)
    {
        $id = $param['id'] ?? 0;
        if (!$id) {
            $this->save($param);
        } else {
            $info = $this->where('id', $id)->find();
            if (empty($info)) {
                throw new ValidateException('记录不存在');
            }
            $info->save($param);
        }
        return true;
    }

    public function del(array $ids)
    {
        return self::destroy(function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        });
    }

    public function refreshCourseDictCount(string|int $courseId, string|int $num)
    {
        return $this->update(['vocabularyNum' => $num], ['id' => $courseId]);
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function bookInfo()
    {
        return $this->hasOne(CourseDict::class, 'id', 'courseBook')->where(['courseDictType' => 4]);
    }

    public function difficultInfo()
    {
        return $this->hasOne(CourseDict::class, 'id', 'courseDifficult')->where(['courseDictType' => 3]);
    }

    public function levelInfo()
    {
        return $this->hasOne(CourseDict::class, 'id', 'courseLevel')->where(['courseDictType' => 2]);
    }

    public function typeInfo()
    {
        return $this->hasOne(CourseDict::class, 'id', 'courseType')->where(['courseDictType' => 1]);
    }

}